<template>
  <a-layout class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <!-- 页面头部 -->
    <a-layout-header class="bg-white/90 backdrop-blur-md border-b border-blue-200/50 px-0 h-auto">
      <div class="max-w-7xl mx-auto px-6 py-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-6">
            <h1 class="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              腾讯元宝
            </h1>
            <a-tag color="green" class="flex items-center">
              <template #icon>
                <CheckCircleOutlined />
              </template>
              已连接
            </a-tag>
          </div>

          <div class="flex items-center space-x-4">
            <a-badge count="10000" showZero class="mr-2">
              <span class="text-lg font-semibold text-amber-600">元宝</span>
            </a-badge>
            <a-input-search placeholder="搜索对话记录" class="w-64" @search="onSearch">
              <template #enterButton>
                <SearchOutlined />
              </template>
            </a-input-search>
          </div>
        </div>
      </div>
    </a-layout-header>

    <a-layout-content class="py-6">
      <div class="max-w-7xl mx-auto px-6">
        <a-row :gutter="24">
          <!-- 左侧边栏 - 热门问题 -->
          <a-col :span="6">
            <a-card title="热门问题" :bordered="true" class="h-full shadow-lg" :body-style="{ padding: 0 }">
              <a-list item-layout="horizontal" :data-source="popularQuestions" class="overflow-y-auto max-h-[70vh]">
                <template #renderItem="{ item, index }">
                  <a-list-item class="p-4 border-b border-gray-100 hover:bg-blue-50 cursor-pointer transition-colors"
                    @click="selectQuestion(item)">
                    <a-list-item-meta :description="item">
                      <template #title>
                        <div class="flex items-center">
                          <QuestionCircleOutlined class="text-blue-500 mr-2" />
                          <span class="text-sm font-medium">问题 {{ index + 1 }}</span>
                        </div>
                      </template>
                    </a-list-item-meta>

                    <!-- 操作按钮（三个点） -->
                    <template #actions>
                      <a-dropdown :trigger="['click']">
                        <a-button type="text" size="small" @click.stop>
                          <MoreOutlined />
                        </a-button>
                        <template #overlay>
                          <a-menu>
                            <a-menu-item key="batch" @click="handleBatchOperation(item)">
                              <template #icon>
                                <AppstoreOutlined />
                              </template>
                              批量操作
                            </a-menu-item>
                            <a-menu-item key="move" @click="handleMoveToGroup(item)">
                              <template #icon>
                                <FolderOutlined />
                              </template>
                              移动到分组
                            </a-menu-item>
                            <a-menu-item key="edit" @click="handleEditName(item)">
                              <template #icon>
                                <EditOutlined />
                              </template>
                              编辑名称
                            </a-menu-item>
                            <a-menu-item key="share" @click="handleShare(item)">
                              <template #icon>
                                <ShareAltOutlined />
                              </template>
                              分享
                            </a-menu-item>
                            <a-menu-item key="pin" @click="handlePin(item)">
                              <template #icon>
                                <PushpinOutlined />
                              </template>
                              置顶
                            </a-menu-item>
                            <a-menu-divider />
                            <a-menu-item key="delete" danger @click="handleDelete(item)">
                              <template #icon>
                                <DeleteOutlined />
                              </template>
                              删除
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </a-dropdown>
                    </template>
                  </a-list-item>
                </template>
              </a-list>
            </a-card>
          </a-col>

          <!-- 右侧主内容区域 -->
          <a-col :span="18">
            <a-card class="shadow-lg h-[75vh] flex flex-col" :body-style="{
              padding: 0,
              display: 'flex',
              flexDirection: 'column',
              height: '100%'
            }">
              <!-- 工具栏 -->
              <div class="border-b border-gray-200 p-4 flex items-center justify-between bg-gray-50">
                <div class="flex items-center space-x-4">
                  <div class="flex items-center space-x-2">
                    <a-progress :percent="progress" :show-info="false" size="small" class="w-32" stroke-color="#52c41a" />
                    <span class="text-sm font-medium text-gray-700">{{ progress }}%</span>
                  </div>

                  <a-tag color="blue" class="flex items-center">
                    <RocketOutlined class="mr-1" />
                    纳米AI
                  </a-tag>

                  <div class="flex items-center space-x-2 text-sm text-gray-600">
                    <span>6.3K/s</span>
                    <a-tag color="green" class="m-0">+0.9K/s</a-tag>
                  </div>
                </div>

                <a-space>
                  <a-tooltip title="全屏">
                    <a-button type="text" @click="toggleFullscreen" class="flex items-center">
                      <template #icon>
                        <FullscreenOutlined v-if="!isFullscreen" />
                        <FullscreenExitOutlined v-else />
                      </template>
                    </a-button>
                  </a-tooltip>

                  <a-tooltip title="新建会话">
                    <a-button type="text" @click="createNewSession" class="flex items-center">
                      <template #icon>
                        <PlusOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>

                  <a-tooltip title="临时会话">
                    <a-button type="text" @click="createTempSession" class="flex items-center">
                      <template #icon>
                        <ClockCircleOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>

                  <a-button type="primary" ghost @click="toggleDeepThinking">
                    <template #icon>
                      <BulbOutlined />
                    </template>
                    {{ deepThinking ? '思考中...' : '深度思考' }}
                  </a-button>
                  <a-button type="primary" ghost>
                    <template #icon>
                      <WifiOutlined />
                    </template>
                    联网搜索
                  </a-button>
                  <a-button type="primary" ghost>
                    <template #icon>
                      <AppstoreOutlined />
                    </template>
                    软件
                  </a-button>
                </a-space>
              </div>

              <!-- 聊天消息区域 -->
              <div class="flex-1 overflow-hidden">
                <div ref="messagesContainer" class="h-full overflow-y-auto p-6">
                  <!-- 空状态 -->
                  <a-empty v-if="messages.length === 0 && !isLoading" description="开始与AI对话，探索智能交互的乐趣"
                    class="h-full flex items-center justify-center">
                    <template #image>
                      <div class="text-6xl mb-4">🤖</div>
                    </template>
                  </a-empty>

                  <!-- 消息列表 -->
                  <div v-else class="space-y-6">
                    <div v-for="message in messages" :key="message.id" class="flex gap-4 transition-all duration-300"
                      :class="message.role === 'user' ? 'justify-end' : 'justify-start'">
                      <!-- AI消息 -->
                      <div v-if="message.role === 'assistant'" class="flex gap-3 max-w-[80%]">
                        <a-avatar size="large" class="bg-gradient-to-br from-green-400 to-blue-500 shadow-md">
                          <template #icon>
                            <RobotOutlined />
                          </template>
                        </a-avatar>

                        <a-card class="max-w-full shadow-sm border-0 bg-gray-50" :body-style="{ padding: '16px' }">
                          <div class="whitespace-pre-wrap text-gray-800 leading-relaxed">
                            {{ message.content }}
                          </div>
                          <div class="flex items-center justify-between mt-3 text-xs text-gray-500">
                            <span>{{ formatTime(message.timestamp) }}</span>
                            <a-tag v-if="message.model" color="blue" size="small">
                              {{ getModelName(message.model) }}
                            </a-tag>
                          </div>
                        </a-card>
                      </div>

                      <!-- 用户消息 -->
                      <div v-else class="flex gap-3 max-w-[80%]">
                        <a-card class="max-w-full shadow-sm border-0 bg-blue-500 text-white"
                          :body-style="{ padding: '16px' }">
                          <div class="whitespace-pre-wrap leading-relaxed">
                            {{ message.content }}
                          </div>
                          <div class="text-blue-100 text-xs mt-3">
                            {{ formatTime(message.timestamp) }}
                          </div>
                        </a-card>

                        <a-avatar size="large" class="bg-gradient-to-br from-blue-400 to-purple-500 shadow-md">
                          你
                        </a-avatar>
                      </div>
                    </div>

                    <!-- 加载状态 -->
                    <div v-if="isLoading" class="flex gap-4 animate-pulse">
                      <a-avatar size="large" class="bg-gradient-to-br from-green-400 to-blue-500 shadow-md">
                        <template #icon>
                          <RobotOutlined />
                        </template>
                      </a-avatar>

                      <a-card class="max-w-full shadow-sm border-0 bg-gray-50" :body-style="{ padding: '16px' }">
                        <a-space>
                          <a-spin size="small" />
                          <span class="text-gray-600">AI正在思考中...</span>
                        </a-space>
                      </a-card>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 消息输入区域 -->
              <div class="border-t border-gray-200 p-6 bg-gray-50">
                <a-row :gutter="16" align="middle">
                  <a-col :flex="1">
                    <a-textarea v-model:value="userInput" :disabled="isLoading"
                      placeholder="和元宝说点什么（Enter发送，Shift+Enter换行）" :auto-size="{ minRows: 2, maxRows: 4 }"
                      @pressEnter="handlePressEnter" class="rounded-2xl" />
                  </a-col>
                  <a-col :span="4">
                    <a-space direction="vertical" class="w-full">
                      <a-button type="primary" @click="handleSendMessage" :loading="isLoading"
                        :disabled="!userInput.trim()" class="w-full rounded-2xl h-12 font-medium">
                        <template #icon>
                          <SendOutlined />
                        </template>
                        发送
                      </a-button>
                      <a-button @click="clearChat" :disabled="messages.length === 0" class="w-full rounded-2xl">
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                        清空
                      </a-button>
                    </a-space>
                  </a-col>
                </a-row>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="ts">
import {
  CheckCircleOutlined,
  SearchOutlined,
  QuestionCircleOutlined,
  RocketOutlined,
  BulbOutlined,
  WifiOutlined,
  AppstoreOutlined,
  RobotOutlined,
  SendOutlined,
  DeleteOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  MoreOutlined,
  AppstoreOutlined as AppstoreIcon,
  FolderOutlined,
  EditOutlined,
  ShareAltOutlined,
  PushpinOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
// 类型定义
interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  model?: string
}

// 响应式数据
const userInput = ref('')
const messages = ref<Message[]>([])
const isLoading = ref(false)
const isConnected = ref(true)
const selectedModel = ref('qwen-plus')
const temperature = ref(0.7)
const maxTokens = ref(2000)
const progress = ref(87)
const deepThinking = ref(false)
const isFullscreen = ref(false)
const messagesContainer = ref<HTMLDivElement>()

// 使用认证store
const authStore = useAuthStore()

// 热门问题列表（从您提供的图片中提取）
const popularQuestions = [
  '本科转计算机是否需成考深造',
  '地球生命还能维持多久',
  '高级前端Ypack面试题',
  '重金属排出途径探讨',
  'JS元素滚动与返回顶部实现',
  '高情商回复邀约女生',
  'React项目打包优化配置',
  '高级前端面试题160道',
  '线下加女生微信技巧',
  '星座及上升星座查询',
  'PPT制作支持服务',
  '成考跨专业转计算机可行',
  '计划因变故失效规律',
  'React核心机制虚拟DOM',
  '性癖的定义与解析',
  'React修改深层对象状态',
  '生辰八字排盘分析',
  '月经血块减小方法',
  '成年古牧每日喂食量',
  '月经期减少血块方法',
  '健身后月经提前分析',
  '高情商回应中午好',
  '真诚回应存钱买车话题',
  '男性176cm135斤BMI值'
]

// 模型选项
const modelOptions = [
  { label: '通义千问 Plus', value: 'qwen-plus' },
  { label: '通义千问 Max', value: 'qwen-max' },
  { label: 'DeepSeek Coder', value: 'deepseek-coder' },
  { label: 'LLaMA 8B', value: 'llama-3-8b-instruct' }
]

// Token验证函数
const validateToken = () => {
  const token = authStore.token
  const currentUser = authStore.currentUser

  // 基础检查
  if (!token || !currentUser) {
    return {
      isValid: false,
      message: '请先登录后再发送消息'
    }
  }
}

// 发送消息函数（添加Token验证）
const handleSendMessage = async () => {

  validateToken()
  // 原有的发送逻辑
  await sendMessage()
}

// 原有的发送消息函数
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  const userMessage: Message = {
    id: Date.now().toString(),
    role: 'user',
    content: userInput.value,
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const currentInput = userInput.value
  userInput.value = ''
  isLoading.value = true

  try {
    // 调用AI接口（使用Prisma保存消息）
    const { data, error } = await $fetch('/api/ai/chat', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      },
      body: {
        messages: [
          ...messages.value.map(msg => ({
            role: msg.role,
            content: msg.content
          }))
        ],
        model: selectedModel.value,
        temperature: temperature.value,
        max_tokens: maxTokens.value,
        userId: authStore.currentUser.id // 添加用户ID用于Prisma关联
      }
    })

    if (error.value) {
      throw new Error(error.value.message)
    }

    if (data.value?.success) {
      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: data.value.data.choices[0].message.content,
        timestamp: new Date(),
        model: selectedModel.value
      }
      messages.value.push(aiMessage)

      // 保存对话记录到数据库（使用Prisma）
      await saveConversationToDB(userMessage, aiMessage)
    }
  } catch (error) {
    console.error('AI对话失败:', error)
    // 显示错误消息
    messages.value.push({
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: '抱歉，我暂时无法响应。请稍后再试或检查网络连接。',
      timestamp: new Date()
    })
  } finally {
    isLoading.value = false
  }
}

// 使用Prisma保存对话记录
const saveConversationToDB = async (userMessage: Message, aiMessage: Message) => {
  try {
    await $fetch('/api/conversations', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      },
      body: {
        userId: authStore.currentUser.id,
        userMessage: userMessage.content,
        aiMessage: aiMessage.content,
        model: selectedModel.value,
        temperature: temperature.value
      }
    })
  } catch (error) {
    console.error('保存对话记录失败:', error)
  }
}

// 选择问题
const selectQuestion = (question: string) => {
  userInput.value = question
  handleSendMessage() // 使用带验证的发送函数
}

// 搜索功能
const onSearch = (value: string) => {
  console.log('搜索:', value)
}

// 清空对话
const clearChat = () => {
  messages.value = []
  userInput.value = ''
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 新建会话
const createNewSession = () => {
  messages.value = []
  userInput.value = ''
  message.success('新会话已创建')
}

// 临时会话
const createTempSession = () => {
  messages.value = []
  userInput.value = ''
  message.info('临时会话已创建（不会保存到历史记录）')
}

// 深度思考切换
const toggleDeepThinking = () => {
  deepThinking.value = !deepThinking.value
  temperature.value = deepThinking.value ? 0.9 : 0.7
  message.info(`深度思考模式${deepThinking.value ? '开启' : '关闭'}`)
}

// 热门问题操作函数
const handleBatchOperation = (question: string) => {
  message.info(`批量操作: ${question}`)
}

const handleMoveToGroup = (question: string) => {
  message.info(`移动到分组: ${question}`)
}

const handleEditName = (question: string) => {
  message.info(`编辑名称: ${question}`)
}

const handleShare = (question: string) => {
  message.info(`分享: ${question}`)
}

const handlePin = (question: string) => {
  message.info(`置顶: ${question}`)
}

const handleDelete = (question: string) => {
  message.info(`删除: ${question}`)
}

// 格式化时间
const formatTime = (date: Date) => {
  return new Date(date).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取模型显示名称
const getModelName = (model: string) => {
  const modelMap: Record<string, string> = {
    'qwen-plus': '千问Plus',
    'qwen-max': '千问Max',
    'deepseek-coder': 'DeepSeek',
    'llama-3-8b-instruct': 'LLaMA'
  }
  return modelMap[model] || model
}

// 键盘快捷键
const handlePressEnter = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    if (event.shiftKey) {
      return // Shift+Enter 换行
    } else {
      event.preventDefault()
      handleSendMessage() // 使用带验证的发送函数
    }
  }
}

// 自动滚动到底部
watch(() => [...messages.value], () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}, { deep: true, immediate: true })

// 初始化示例对话
onMounted(() => {
  messages.value.push({
    id: '1',
    role: 'assistant',
    content: '你好！我是腾讯元宝AI助手，很高兴为你服务。有什么问题可以问我哦！',
    timestamp: new Date(),
    model: 'deepseek'
  })
})
</script>

<style scoped>
/* 自定义样式增强 */
:deep(.ant-layout-header) {
  line-height: 1.5;
  padding: 0;
}

:deep(.ant-card) {
  border-radius: 12px;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 20px;
}

:deep(.ant-list-item) {
  padding: 12px 20px;
}

:deep(.ant-btn) {
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-btn-round) {
  border-radius: 20px;
}

:deep(.ant-input) {
  border-radius: 8px;
}

:deep(.ant-tag) {
  border-radius: 6px;
  display: flex;
  align-items: center;
}

:deep(.ant-avatar) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 消息卡片阴影效果 */
:deep(.ant-card) {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* 滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 6px;
}

:deep(::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}
</style>